<?php
namespace app\controller;

use app\BaseController;
use think\facade\Log;
use think\facade\View;
//use think\facade;

class ApplePayCallback extends BaseController
{
    public function index()
    {
        try {
            // 获取苹果内购回调的 POST 数据
            $input = file_get_contents('php://input');
            $data = json_decode($input, true);

            // 记录回调数据日志，方便后续排查问题
            Log::info('Apple Pay Callback Data: '. $input);

            // 验证数据完整性
            if (empty($data) ||!isset($data['receipt-data'])) {
                Log::error('Invalid Apple Pay callback data');
                return json(['status' => 0, 'msg' => 'Invalid data']);
            }

            // 获取收据数据
            $receiptData = $data['receipt-data'];

            // 验证收据
            $isValid = $this->verifyReceipt($receiptData);

            if ($isValid) {
                // 收据验证成功，处理订单逻辑
                $this->handleOrder($receiptData);
                return json(['status' => 1, 'msg' => 'Success']);
            } else {
                Log::error('Apple Pay receipt verification failed');
                return json(['status' => 0, 'msg' => 'Receipt verification failed']);
            }
        } catch (\Exception $e) {
            // 记录异常日志
            Log::error('Apple Pay callback error: '. $e->getMessage());
            return json(['status' => 0, 'msg' => 'Error occurred']);
        }
    }

    private function verifyReceipt($receiptData)
    {
        // 苹果生产环境验证地址
        $productionUrl = 'https://buy.itunes.apple.com/verifyReceipt';
        // 苹果沙盒环境验证地址
        $sandboxUrl = 'https://sandbox.itunes.apple.com/verifyReceipt';

        // 先尝试在生产环境验证
        $response = $this->sendRequest($productionUrl, $receiptData);
        $result = json_decode($response, true);

        if (isset($result['status']) && $result['status'] == 21007) {
            // 如果返回 21007，表示这是一个沙盒环境的收据，再尝试在沙盒环境验证
            $response = $this->sendRequest($sandboxUrl, $receiptData);
            $result = json_decode($response, true);
        }

        return isset($result['status']) && $result['status'] == 0;
    }

    private function sendRequest($url, $receiptData)
    {
        $ch = curl_init($url);
        $data = json_encode(['receipt-data' => $receiptData]);

        curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
        curl_setopt($ch, CURLOPT_POST, true);
        curl_setopt($ch, CURLOPT_POSTFIELDS, $data);
        curl_setopt($ch, CURLOPT_HTTPHEADER, ['Content-Type: application/json']);

        $response = curl_exec($ch);
        curl_close($ch);

        return $response;
    }

    private function handleOrder($receiptData)
    {
        // 这里处理订单逻辑，例如更新订单状态、给用户增加权益等
        // 示例：更新订单状态为已支付
        // 假设订单表为 order，有字段 order_id 和 status
        // $orderId = $this->getOrderIdFromReceipt($receiptData);
        // \think\facade\Db::name('order')->where('order_id', $orderId)->update(['status' => 1]);
    }

    private function getOrderIdFromReceipt($receiptData)
    {
        // 从收据数据中解析出订单 ID
        // 这里需要根据实际的收据数据结构进行解析
        return null;
    }
}
